//
//  ReceiverAlertView.m
//  TengyunStation
//
//  Created by Johnny on 15/8/25.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "ReceiverAlertView.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "PositionDBModel.h"
#import "ComMethod.h"

#define ViewWidth           272.0
#define ViewHeight          220.0
#define ButtonHeight        44.0
#define AnimateDuration     0.25

@interface ReceiverAlertView ()<SocketRequestDelegate> {
    SocketRequest *_socketRequest;
}

@end

@implementation ReceiverAlertView

- (id)initWithUploadExpress:(UploadExpress *)uploadExpress {
    self = [super initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - ViewWidth)/2.0, ([UIScreen mainScreen].bounds.size.height - ViewHeight)/2.0, ViewWidth, ViewHeight)];
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = 5;
    self.clipsToBounds = YES;
    if (self) {
        _uploadExpress = uploadExpress;
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        
        _positionLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 280, 20)];
        _positionLabel.textColor = [UIColor orangeColor];
        _positionLabel.font = [UIFont systemFontOfSize:19];
        _positionLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_positionLabel];
        
        _expressIdTextField = [[UITextField alloc] initWithFrame:CGRectMake(50, 50, 200, 30)];
        _expressIdTextField.placeholder = @"请输入运单号";
        _expressIdTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _expressIdTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _expressIdTextField.returnKeyType = UIReturnKeyNext;
        _expressIdTextField.font = [UIFont systemFontOfSize:15];
        _expressIdTextField.delegate = self;
        _expressIdTextField.text = uploadExpress.expressId;
        _expressIdTextField.autocorrectionType = UITextAutocorrectionTypeNo;
        [self addSubview:_expressIdTextField];
        
        _phoneTextField = [[ReceiverTextField alloc] initWithFrame:CGRectMake(50, 90, 200, 30)];
        _phoneTextField.placeholder = @"请输入收件人手机号";
        _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _phoneTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _phoneTextField.returnKeyType = UIReturnKeyNext;
        _phoneTextField.font = [UIFont systemFontOfSize:15];
        _phoneTextField.receiverDelegate = self;
        _phoneTextField.autocorrectionType = UITextAutocorrectionTypeNo;
        [self addSubview:_phoneTextField];
        
        _floorTextField = [[UITextField alloc] initWithFrame:CGRectMake(50, 130, 85, 30)];
        _floorTextField.placeholder = @"几号楼";
        _floorTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _floorTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _floorTextField.returnKeyType = UIReturnKeyNext;
        _floorTextField.font = [UIFont systemFontOfSize:15];
        _floorTextField.delegate = self;
        _floorTextField.autocorrectionType = UITextAutocorrectionTypeNo;
        [self addSubview:_floorTextField];
        
        UILabel *sepLabel = [[UILabel alloc] initWithFrame:CGRectMake(115, 130, 30, 30)];
        sepLabel.textAlignment = NSTextAlignmentCenter;
        sepLabel.textColor = [UIColor darkGrayColor];
        sepLabel.text = @"#";
        sepLabel.font = [UIFont boldSystemFontOfSize:17];
        [self addSubview:sepLabel];
        
        _roomTextField = [[UITextField alloc] initWithFrame:CGRectMake(145, 130, 170, 30)];
        _roomTextField.placeholder = @"几号房";
        _roomTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _roomTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _roomTextField.returnKeyType = UIReturnKeyDone;
        _roomTextField.font = [UIFont systemFontOfSize:15];
        _roomTextField.delegate = self;
        _roomTextField.autocorrectionType = UITextAutocorrectionTypeNo;
        [self addSubview:_roomTextField];
        
        [self creatButtonY:(ViewHeight - ButtonHeight) CancelButtonTitle:@"取消" sureButtonTitle:@"确定"];
    }
    return self;
}

#pragma mark 创建取消和确认按钮
- (void)creatButtonY:(float)Y CancelButtonTitle:(NSString *)cancleButtonTitle sureButtonTitle:(NSString *)sureButtonTitle {
    UILabel *lineLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(0, Y, ViewWidth, 1)];
    lineLabel1.backgroundColor = [UIColor lightGrayColor];
    [self addSubview:lineLabel1];
    CGRect cancelRect = CGRectMake(0, Y + 1, ViewWidth/2.0 - 0.5, ButtonHeight);
    UIButton *cancelButton = [self customFrame:cancelRect Title:cancleButtonTitle BtnTag:0];
    [self addSubview:cancelButton];
    
    UILabel *lineLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(ViewWidth/2.0 - 0.5, Y + 1, 1, ButtonHeight)];
    lineLabel2.backgroundColor = [UIColor lightGrayColor];
    [self addSubview:lineLabel2];
    
    CGRect sureRect = CGRectMake(ViewWidth/2.0 + 0.5, Y + 1, ViewWidth/2.0 - 0.5, ButtonHeight);
    UIButton *sureButton = [self customFrame:sureRect Title:sureButtonTitle BtnTag:1];
    [self addSubview:sureButton];
}

- (UIButton *)customFrame:(CGRect)frame Title:(NSString *)title BtnTag:(NSInteger)tag {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    if (tag == 0) {
        [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    } else if (tag == 1) {
        [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    }
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    button.tag = tag;
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

- (void)buttonAction:(UIButton *)button {
    if (button.tag == 0) {//取消
        if ([_delegate respondsToSelector:@selector(cancelReceiverAlertViewInput)]) {
            [_delegate cancelReceiverAlertViewInput];
        }
        [self removeReceiverAlertView];
    } else if (button.tag == 1) {//成功
        [self endEditing:YES];
        if (_expressIdTextField.text.length <= 0) {
            [DSToast showText:@"请输入运单号" InView:self];
        } else if ([self.codeList containsObject:_expressIdTextField.text]) {
            [DSToast showText:@"此运单重复" InView:self];
        } else if (_phoneTextField.text.length <= 0) {
            [DSToast showText:@"请输入手机号" InView:self];
        } else if (![ComMethod judgeIsLegal:_phoneTextField.text Limit:TelephoneLimit]) {
            [DSToast showText:@"请输入正确的11位手机号" InView:self];
        } else if (![ComMethod judgeIsLegal:_expressIdTextField.text Limit:ExpressIdLimit]) {
            [DSToast showText:@"请输入正确的运单号" InView:self];
        } else if (![ComMethod judgeIsLegal:_floorTextField.text Limit:FloorLimit]) {
            [DSToast showText:@"请输入正确的楼号" InView:self];
        } else if (![ComMethod judgeIsLegal:_roomTextField.text Limit:FloorLimit]) {
            [DSToast showText:@"请输入正确的房号" InView:self];
        } else {
            _uploadExpress.expressId = _expressIdTextField.text;
            _uploadExpress.receiver = _phoneTextField.receiverModel;
            [self uploadExpressSocket];
        }
    }
}

//移除alertWindow
- (void)removeReceiverAlertView {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [self endEditing:YES];
    [_alertWindow resignFirstResponder];
    [_alertWindow resignKeyWindow];
    _alertWindow.alpha = 0;
    _alertWindow = nil;
}

- (void)show {
    if (!_alertWindow) {
        _alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _alertWindow.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        _alertWindow.windowLevel = UIWindowLevelNormal;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    if ([Singleton shareInstance].position == nil) {
        [self applyforPositionSocket];//申请库位号
    } else {
        _positionLabel.text = [NSString stringWithFormat:@"编号：%@",[Singleton shareInstance].position.positionNumber];
        [self textFieldBecomeFirstResponder];
    }
    [_alertWindow addSubview:self];
    [_alertWindow makeKeyAndVisible];
}
//编辑框自动响应弹出键盘
- (void)textFieldBecomeFirstResponder {
    if (_uploadExpress.expressId == nil) {
        [_expressIdTextField becomeFirstResponder];
    } else {
        [_phoneTextField becomeFirstResponder];
    }
}

#pragma mark Socket请求
//申请库位号
- (void)applyforPositionSocket {
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STS3"]];
    [mutableData appendBytes:[SocketMethod checkLegal:@"1"] length:1];//申请
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    NSData *hexData = [SocketMethod hexDataWithLength:0];
    [mutableData appendData:hexData];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}
//快件上传
- (void)uploadExpressSocket {
    [ToastActivity makeActivity:@"快件上传中..." InView:self];
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STS4"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.userId] length:64];
    NSString *address = @"";
    if (_uploadExpress.receiver.floor.length > 0) {
        address = [NSString stringWithFormat:@"%@#%@",[SocketMethod checkNull:_uploadExpress.receiver.floor],[SocketMethod checkNull:_uploadExpress.receiver.room]];
    } else {
        address = [SocketMethod checkNull:_uploadExpress.receiver.room];
    }
    NSString *contentString = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%@,%ld,%@,%@,%@,%@",[SocketMethod checkNull:_uploadExpress.expresser.expressCompanyId],[SocketMethod checkNull:_uploadExpress.expresser.expressCompanyName],[SocketMethod checkNull:_uploadExpress.expressId],[SocketMethod checkNull:_uploadExpress.inwayExpressId],[SocketMethod checkNull:_uploadExpress.expresser.expresserId],[SocketMethod checkNull:_uploadExpress.expresser.expresserName],[SocketMethod checkNull:_uploadExpress.expresser.telephone],(long)_uploadExpress.expressSendType,[SocketMethod checkNull:_uploadExpress.batchNo],[SocketMethod checkNull:_uploadExpress.receiver.telephone],address,[SocketMethod checkNull:[Singleton shareInstance].position.positionNumber]];
    DLog(@"contentString:%@",contentString);
    NSData *contentData = [contentString dataUsingEncoding:NSUTF8StringEncoding];
    [mutableData appendData:[SocketMethod hexDataWithLength:contentData.length]];
    [mutableData appendData:contentData];
    [_socketRequest addSocketData:mutableData SocketTag:2];
}

#pragma mark Notification
- (void)showKeyboard:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    float Y = [UIScreen mainScreen].bounds.size.height - keyboardSize.height - self.frame.size.height;
    if (Y < 0) {
        Y = 0;
    }
    [UIView animateWithDuration:AnimateDuration animations:^{
        self.frame = CGRectMake(self.frame.origin.x, Y/2.0, self.frame.size.width, self.frame.size.height);
    }];
}

- (void)hideKeyboard:(NSNotification *)notification {
    [UIView animateWithDuration:AnimateDuration animations:^{
        self.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - self.frame.size.width)/2.0, ([UIScreen mainScreen].bounds.size.height - self.frame.size.height)/2.0, self.frame.size.width, self.frame.size.height);
    }];
}

#pragma mark ReceiverTextFieldDelegate
- (void)didFinishEditingReceiverTextField {
    _floorTextField.text = _phoneTextField.receiverModel.floor;
    _roomTextField.text = _phoneTextField.receiverModel.room;
    if (_phoneTextField.receiverModel.floor == nil) {
        [_floorTextField becomeFirstResponder];
    } else if (_phoneTextField.receiverModel.room == nil) {
        [_roomTextField becomeFirstResponder];
    } else {
        [_phoneTextField resignFirstResponder];
    }
}

#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _expressIdTextField) {
        [_phoneTextField becomeFirstResponder];
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == _phoneTextField) {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:TelephoneLimit] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if (![string isEqualToString:filtered]) {
            return NO;
        }
    } else if (textField == _expressIdTextField) {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ExpressIdLimit] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if (![string isEqualToString:filtered]) {
            return NO;
        }
    } else {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:FloorLimit] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if (![string isEqualToString:filtered]) {
            return NO;
        }
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == _floorTextField) {
        _phoneTextField.receiverModel.floor = textField.text;
    } else if (textField == _roomTextField) {
        _phoneTextField.receiverModel.room = textField.text;
    }
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    [ToastActivity dismissInView:self];
    if ([code isEqualToString:SuccessSocket]) {
        if (socket.socketTag == 1) {//申请库位号
            NSString *positionNumber  = [SocketMethod stringData:data];
            PositionDBModel *position = [[PositionDBModel alloc] init];
            position.positionNumber = positionNumber;
            [Singleton shareInstance].position = nil;
            position.websiteId = [Singleton shareInstance].userMessage.websiteId;
            [position save];
            [Singleton shareInstance].position = position;
            _positionLabel.text = [NSString stringWithFormat:@"编号：%@",position.positionNumber];
            [self textFieldBecomeFirstResponder];
        } else if (socket.socketTag == 2) {//面单录入
            [_phoneTextField.receiverModel saveReceiverDBModel];
            if ([_delegate respondsToSelector:@selector(successUploadExpress:)]) {
                [_delegate successUploadExpress:_uploadExpress];
            }
            [[Singleton shareInstance].position deleteObject];
            [Singleton shareInstance].position = nil;
            [self performSelector:@selector(removeReceiverAlertView) withObject:nil afterDelay:1];
        }
    } else {
        [DSToast showText:msg InView:self];
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [ToastActivity dismissInView:self];
    [DSToast showText:msg InView:self];
}

- (void)dealloc {
    _positionLabel = nil;
    _expressIdTextField = nil;
    _phoneTextField = nil;
    _floorTextField = nil;
    _roomTextField = nil;
    _delegate = nil;
}

@end
